#include "bldc.h"

void BLDC_Configuration(void)
{
  __SYSCTRL_ATIM_CLK_ENABLE();
  __SYSCTRL_GPIOA_CLK_ENABLE();
  __SYSCTRL_GPIOB_CLK_ENABLE();
  // 上桥引脚
  GPIO_InitTypeDef GPIO_InitStruct = {0};
  GPIO_InitStruct.IT = GPIO_IT_NONE;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pins = PWM_AP_PIN | PWM_BP_PIN;
  GPIO_Init(CW_GPIOB, &GPIO_InitStruct);
  GPIO_InitStruct.Pins = PWM_CP_PIN;
  GPIO_Init(CW_GPIOA, &GPIO_InitStruct);
  PB00_AFx_ATIMCH1();
  PB01_AFx_ATIMCH2();
  PA03_AFx_ATIMCH3();

  // 下桥引脚
  GPIO_InitStruct.IT = GPIO_IT_NONE;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pins = PWM_AN_PIN | PWM_CN_PIN;
  GPIO_Init(CW_GPIOA, &GPIO_InitStruct);
  GPIO_InitStruct.Pins = PWM_BN_PIN;
  GPIO_Init(CW_GPIOB, &GPIO_InitStruct);

  PWM_AL_OFF;
  PWM_BL_OFF;
  PWM_CL_OFF;

  ATIM_InitTypeDef ATIM_InitStruct;
  ATIM_OCInitTypeDef ATIM_OCInitStruct = {0};
  ATIM_InitStruct.BufferState = ENABLE;                            // 使能缓存寄存器
  ATIM_InitStruct.CounterAlignedMode = ATIM_COUNT_ALIGN_MODE_EDGE; // 边沿对齐
  ATIM_InitStruct.CounterDirection = ATIM_COUNTING_UP;             // 向上计数；
  ATIM_InitStruct.CounterOPMode = ATIM_OP_MODE_REPETITIVE;         // 连续运行模式
  ATIM_InitStruct.Prescaler = 1 - 1;                               // 计算时钟 48 MHz
  ATIM_InitStruct.ReloadValue = PWM_PERIOD - 1;                    // PWM_TS = 2399
  ATIM_InitStruct.RepetitionCounter = 0;
  ATIM_Init(&ATIM_InitStruct);

  ATIM_OCInitStruct.BufferState = ENABLE;
  ATIM_OCInitStruct.OCComplement = DISABLE;
  ATIM_OCInitStruct.OCFastMode = DISABLE;
  ATIM_OCInitStruct.OCInterruptState = DISABLE;
  ATIM_OCInitStruct.OCMode = ATIM_OCMODE_PWM1;
  ATIM_OCInitStruct.OCPolarity = ATIM_OCPOLARITY_NONINVERT;
  ATIM_OC1Init(&ATIM_OCInitStruct);
  ATIM_OC2Init(&ATIM_OCInitStruct);
  ATIM_OC3Init(&ATIM_OCInitStruct);
  ATIM_OC4Init(&ATIM_OCInitStruct);

  ATIM_SetCompare1(PWM_PERIOD / 2);
  ATIM_SetCompare2(PWM_PERIOD / 2);
  ATIM_SetCompare3(PWM_PERIOD / 2);
  ATIM_SetCompare4(PWM_PERIOD / 2);

  ATIM_CH1Config(ENABLE);
  ATIM_CH2Config(ENABLE);
  ATIM_CH3Config(ENABLE);
  ATIM_CH4Config(ENABLE);

  ATIM_CtrlPWMOutputs(ENABLE);
  ATIM_Cmd(ENABLE);
}

INIT_EXPORT(BLDC_Configuration, "5");